package com.wangyb.wework.service.contact;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wangyb.wework.bo.ContactAddwayState;
import com.wangyb.wework.enums.ContactAddwayStateEnum;
import com.wangyb.wework.entity.contact.WwGroupchatAutoPull;
import com.wangyb.wework.entity.employee.WwEmployee;
import com.wangyb.wework.service.IWwEmployeeService;
import com.wangyb.wework.utils.DownUploadQueueUtils;
import com.wangyb.wework.utils.FileUtils;
import com.wangyb.wework.utils.WxApiUtils;
import com.wangyb.wework.wxApi.CreateContactWayResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: wangyb
 * @Date: 2021/7/19 2:55 下午
 */
@Slf4j
@Component
@EnableAsync
public class GroupchatAutoPullSyncLogic implements IGroupchatAutoPullSyncLogic {
	@Autowired
	private IWwEmployeeService iWwEmployeeService;
	@Autowired
	private IWwGroupchatAutoPullService iWwGroupchatAutoPullService;

	/**
	 * 创建微信 配置客户联系「联系我」方式 二维码
	 */
	@Override
	public void onCreateWxAddContactWayQrcode(WwGroupchatAutoPull entity){
		Long corpId = entity.getCorpId();
		boolean skipVerify = entity.getIsVerified() == 2;
		ContactAddwayState state = new ContactAddwayState(ContactAddwayStateEnum.GroupchatAutoPull,entity.getId());
		Set<String> wxUserIdSet = getWxUserIdSet(entity);
		CreateContactWayResp resp = WxApiUtils.requestCreateContactWay(corpId, skipVerify, state, wxUserIdSet);
		log.debug("resp.config_id="+resp.getConfigId());
		log.debug("resp.qrcode="+resp.getQrCode());
		String qrcodeUrl = resp.getQrCode();
		String wxConfigId = resp.getConfigId();

		// 上传图片
		String qrcodeFileName = FileUtils.getFileNameOfContactWayQrCode();
		DownUploadQueueUtils.uploadFileByUrl(qrcodeFileName, qrcodeUrl);

		entity.setQrcodeUrl(qrcodeFileName);
		entity.setWxConfigId(wxConfigId);
		iWwGroupchatAutoPullService.updateById(entity);
	}

	@Override
	public void onUpdateWxAddContactWayQrcode(WwGroupchatAutoPull entity) {
		Long corpId = entity.getCorpId();
		Set<String> wxUserIdSet = getWxUserIdSet(entity);
		boolean skipVerify = entity.getIsVerified() == 2;
		WxApiUtils.requestUpdateContactWay(corpId,entity.getWxConfigId(),skipVerify,wxUserIdSet);
	}
	private Set<String> getWxUserIdSet(WwGroupchatAutoPull entity){
		Set<Long> employeeIdSet = JSON.parseArray(entity.getEmployees(), JSONObject.class)
			.stream()
			.map(jsonObject -> jsonObject.getLong("id"))
			.collect(Collectors.toSet());
		List<WwEmployee> employeeList = iWwEmployeeService.getBaseMapper().selectBatchIds(employeeIdSet);
		Set<String> wxUserIdSet = employeeList.stream().map(e -> e.getWxUserId()).collect(Collectors.toSet());
		return wxUserIdSet;
	}

}
